import React, { useMemo } from 'react'
import { getFileTypeIconSvg } from '@inbiz/utils';
import { Button, Checkbox, Typography } from 'antd';
import type { ICategorySelect } from '../content';
import SecondImg from '../SecondImg'

const folderIcon = getFileTypeIconSvg('.folder');
const { Text } = Typography;
export default function CategoryItemRender({
  item,
  parentItem,
  selected,
  onSelected,
  IsWhether,
  level,
  config,
}: {
  item: any;
  selected: any;
  onSelected: ICategorySelect;
  IsWhether: boolean;
  level: number;
  parentItem: any;
  config: any;
}) {

  const { Value: value, Count: count, } = item
  const { Key: categoryKey, ShowHierarchy } = parentItem
  const checked = useMemo(() => {
    if (item.sectionItemList || (ShowHierarchy == 2 && parentItem.IsGroup)) {
      const keys = item.sectionItemList.map(ele => ele.Key)
      return keys.every(ele => selected.includes(ele))
    }
    return selected.includes(item.Key)
  }, [selected, item])
  const icon = useMemo(() => {
    return categoryKey === 'parentfolderid' || categoryKey === 'fileextname' ? (
      <img
        src={categoryKey === 'parentfolderid' ? folderIcon : getFileTypeIconSvg(value)}
        className="categoryItem-Icon"
      />
    ) : undefined;
  }, [categoryKey, value]);
  const selectItem = () => {
    if (item.sectionItemList||(ShowHierarchy == 2 && parentItem.IsGroup)) {
      const keys = item.sectionItemList.map(ele => ele.Key)
      onSelected(keys, !checked, level, IsWhether)
    } else {
      onSelected([item.Key], !checked, level, IsWhether)
    }
  }

  return useMemo(() => {
    return (
      <li>
        <div
          className={`${IsWhether ? 'categoryMultipleItemBox' : ''} categoryItemBox ${checked ? 'selected' : ''} `}
          onClick={selectItem}
        >
          <Button
            icon={
              <>
                {IsWhether ? <Checkbox checked={checked} /> : undefined}
                {parentItem.ShowHierarchy == 2 ? <SecondImg Icon={item.Icon} /> : icon}
              </>
            }
            size="small"
            shape="round"
            type="text"
            title={count ? `${value} (${count})` : value}
          >
            <Text
              style={{
                minWidth: 30,
                maxWidth:
                  config.sectionDisplayPosition === 'top'
                    ? 80
                    : IsWhether
                      ? 90: 'auto',
                textAlign: 'left',
              }}
              ellipsis
              title={count ? `${value} (${count})` : value}
            >
              {value} {count ? `(${count})` : ''}
            </Text>
          </Button>
        </div>
      </li>
    );
  }, [icon, checked, count, onSelected, item, IsWhether, parentItem]);
}
